﻿using Common.DTO;
using Database.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Database.Repositories
{
    public class IslandQueRepository : RepositoryBase<IslandQue>, IRepository<IslandQueDTO>
    {
        //private readonly IslandQueMapper _queMapper;
        //private readonly IslandMapper _islandMapper;

        public IslandQueRepository()
        {
            //_islandMapper = new IslandMapper();
            //_queMapper = new IslandQueMapper();
            
        }

        public Guid Create(IslandQueDTO que)
        {
            var islandEntity = DbContext.IslandSet.FirstOrDefault(
                x => x.Id == que.Island.Id);
            if (islandEntity == null)
                throw new EntityDoesNotExistException("Island does not exist");

            var characterEntity = DbContext.CharacterSet.FirstOrDefault(
                x => x.Id == que.Character.Id);
            if (characterEntity == null)
                throw new EntityDoesNotExistException("Character does not exist");

            var islandQueEntity = new IslandQue();
            var id = Guid.NewGuid();
            islandQueEntity.Id = id;
            islandQueEntity.IslandId = que.Island.Id;
            islandQueEntity.CharacterId = que.Character.Id;

            DbContext.IslandQueSet.Add(islandQueEntity);
            DbContext.SaveChanges();
            //DbContext.Dispose();

            return id;
        }


        public IslandQueDTO Read(Guid id)
        {
            throw new NotImplementedException();
        }

        public bool Update(IslandQueDTO dto)
        {
            throw new NotImplementedException();
        }

        public bool Delete(Guid id)
        {
            throw new NotImplementedException();
        }


        public bool DeleteAll()
        {
            var allEntites = DbContext.IslandQueSet.Select(x => x).ToList();
            allEntites.ForEach(delegate(IslandQue entity)
            {
                MarkEntityForDeletion(entity);
            });
            return SaveChanges(allEntites.Count);
        }

        public override bool MarkEntityForDeletion(IslandQue entity)
        {
            MarkEntityDependenciesForDeletion();
            //var result = entity.Island.IslandQues.Remove(entity);
            DbContext.IslandQueSet.Remove(entity);
            //DbContext.IslandQueSet.Local.Remove(entity);
            

            return true;
        }
    }
}
